package top.fsb.dataview.service.utils;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.lang.Nullable;
import top.fsb.dataview.service.constant.TokenConstant;
import top.fsb.dataview.service.info.CharPool;
import top.fsb.dataview.service.info.Kv;

import java.util.Map;

import static cn.hutool.core.text.CharSequenceUtil.subPre;

/**
 * 分页工具
 *
 * @author Chill
 */
public class ConditionUtil {

    /**
     * 转化成mybatis plus中的Page
     *
     * @param query 查询条件
     * @return IPage
     */
    public static <T> IPage<T> getPage(Query query) {
        int current = 1,size =10;
        if(query.getCurrent()!=null){
            current =query.getCurrent();
        }

        if(query.getCurrent()!=null){
            size =query.getSize();
        }

        Page<T> page = new Page<>(current, size);
        String[] ascArr = {};
        if(query.getDescs()!=null){
            ascArr = query.getDescs().split(",");
        }

        for (String asc : ascArr) {
            page.addOrder(OrderItem.asc(cleanIdentifier(asc)));
        }

        String[] descArr = {};
        if(query.getDescs()!=null){
            descArr = query.getDescs().split(",");
        }
        for (String desc : descArr) {
            page.addOrder(OrderItem.desc(cleanIdentifier(desc)));
        }
        return page;
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param entity 实体
     * @param <T>    类型
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> getQueryWrapper(T entity) {
        return new QueryWrapper<>(entity);
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param query 查询条件
     * @param clazz 实体类
     * @param <T>   类型
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> query, Class<T> clazz) throws InstantiationException, IllegalAccessException {
        Kv exclude = Kv.create().set(TokenConstant.HEADER, TokenConstant.HEADER)
                .set("current", "current").set("size", "size").set("ascs", "ascs").set("descs", "descs");
        return getQueryWrapper(query, exclude, clazz);
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param query   查询条件
     * @param exclude 排除的查询条件
     * @param clazz   实体类
     * @param <T>     类型
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> query, Map<String, Object> exclude, Class<T> clazz) throws IllegalAccessException, InstantiationException {
        exclude.forEach((k, v) -> query.remove(k));
        QueryWrapper<T> qw = new QueryWrapper<>();
        qw.setEntity(clazz.newInstance());
        SqlKeyword.buildCondition(query, qw);
        return qw;
    }



    /**
     * 获取标识符，用于参数清理
     *
     * @param param 参数
     * @return 清理后的标识符
     */
    @Nullable
    private static String cleanIdentifier(@Nullable String param) {
        if (param == null) {
            return null;
        }
        StringBuilder paramBuilder = new StringBuilder();
        for (int i = 0; i < param.length(); i++) {
            char c = param.charAt(i);
            if (Character.isJavaIdentifierPart(c)) {
                paramBuilder.append(c);
            }
        }
        return paramBuilder.toString();
    }


    /**
     * 获取数据库字段
     *
     * @param column  字段名
     * @param keyword 关键字
     * @return
     */
    private  String getColumn(String column, String keyword) {
        return humpToUnderline(removeSuffix(column, keyword));
    }

    /**
     * 驼峰转下划线
     *
     * @param para 字符串
     * @return {String}
     */
    public static String humpToUnderline(String para) {
        para = firstCharToLower(para);
        StringBuilder sb = new StringBuilder(para);
        int temp = 0;
        for (int i = 0; i < para.length(); i++) {
            if (Character.isUpperCase(para.charAt(i))) {
                sb.insert(i + temp, "_");
                temp += 1;
            }
        }
        return sb.toString().toLowerCase();
    }

    /**
     * 首字母变小写
     *
     * @param str 字符串
     * @return {String}
     */
    public static String firstCharToLower(String str) {
        char firstChar = str.charAt(0);
        if (firstChar >= CharPool.UPPER_A && firstChar <= CharPool.UPPER_Z) {
            char[] arr = str.toCharArray();
            arr[0] += (CharPool.LOWER_A - CharPool.UPPER_A);
            return new String(arr);
        }
        return str;
    }

    /**
     * 去掉指定后缀
     *
     * @param str    字符串
     * @param suffix 后缀
     * @return 切掉后的字符串，若后缀不是 suffix， 返回原字符串
     */
    public static String removeSuffix(CharSequence str, CharSequence suffix) {
        if (StrUtil.isEmpty(str) || StrUtil.isEmpty(suffix)) {
            return StringPool.EMPTY;
        }

        final String str2 = str.toString();
        if (str2.endsWith(suffix.toString())) {
            return subPre(str2, str2.length() - suffix.length());
        }
        return str2;
    }


}
